function MakeLaTeX_table(datamat, rowtit, coltit, corner, tablename, fname, tex_only, outputpath,options)
% MakeLaTeX_table(datamat, rowtit, coltit, corner, tablename, fname, tex_only)
% ============================================
% Original Purpose: Help AJ to make LaTeX tables from Matlab
%
% [Input]:
% Datamat: matrix of data
% Rowtit:  cell array of row title(usually on the left); 
% Coltit:  cell array of column title(on the top); 
% Corner:  string, upper left corner of the graph
% tablename: string of Title name printed on the top of table
% fname: name of the output file
% tex_only: whether or not to typeset the table
% outputpath: if [] or not supplied, copies to current path 
%
% [Output]: 
% Alaways a TeX file contains the LaTeX commands for creating the table
% if tex_only == 0, a PDF version of a table
% 
% [Example]: 
% (1): Quick and Dirty
%       MakeLaTeX_table(rand(4, 6))
%       in this case a TeX file and a PDF version of a table will be
%       created
% output looks like this: 
%               An Example
%       Col.1 Col.2 Col.3 Col.4 Col.5 Col.6
%   Row1 0.10 0.58 0.82 0.65 0.55 0.69
%   Row2 0.13 0.06 0.02 0.73 0.30 0.18
%   Row3 0.94 0.23 0.04 0.65 0.74 0.37
%   Row4 0.96 0.35 0.17 0.45 0.19 0.63
%  This function will by default create row titles, column titles, "corner"
%  and table title
%
% (2): Get ready for importing
% MakeLaTeX_table([1, 2; 3, 5 ], {'blue', 'red'}, {'North', 'South'}, ...
%     'testing', '2-by-2 table', 'table1', 1)
%    Given the tex_only = 1 in this case, the only outpu is a tex file 
%    named "table1.tex" that contains the following 
%    
% 
% ~~~~~~~Contents of TABLE1.tex~~~~~~~~~~~~
% \begin{flushleft}
% \begin{tabular}{|l ||c |c |}
% \hline
% \multicolumn{3}{|c|}{2-by-2 table} \\
% \hline
% testing&North&South\\ \hline
% blue&1.00&2.00\\ \hline
% red&3.00&5.00\\ \hline
% \end{tabular}
% \end{flushleft}
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% This setup makes it easy for user to import this table to his main LaTeX
% article. He/She can do so simply by using the following command: 
% \input(table1.tex)
% 
% [To be Done]: Now only deals with numbers in the table
%               Could extend to symbos
% ============================================
%  RA: Xi Luo
%  Data Created: 05/12/2011
% 
cucd=cd;
fclose('all'); % close all existing
if isnumeric(datamat); 
    isnum = 1; 
elseif iscell(datamat); 
    isnum = 0; 
else
    error('datamat has either to be numeric or a cellarray')
end 
[nrow, ncol] = size(datamat);
if nargin < 2;
    rowtit = strcat('Row ', num2cprec(1:nrow));
end
if nargin < 3;
    coltit = strcat('Col. ', num2cprec(1:ncol));
end
if nargin < 4;
    corner = ' ';
end
if nargin < 5;
    tablename = 'An Example';
end
if nargin < 6;
    fname = 'Example';
end
if nargin < 7;
    tex_only = 0;
end
if nargin < 8 || isempty(outputpath) 
    outputpath=cucd;
end

if nargin < 9 || isempty(options)
    options.orientation = 'portrait';
end

stylestr =  '{|l ||';
for ii = 1:ncol
    stylestr = [stylestr, 'c |' ];
end
stylestr =  [stylestr, '}'];

f1=fopen([fname,'.tex'],'w');
if ~tex_only
    fprintf(f1, ['\\documentclass[',options.orientation, ', 12pt]{report} \n']);
    fprintf(f1, '\\usepackage{rotating} \n');
    fprintf(f1, '\\usepackage{longtable} \n');
    fprintf(f1, '\\setlength{\\oddsidemargin}{-0.25in} \n');
    fprintf(f1, '\\begin{document} \n');
end
fprintf(f1, '\\begin{center} \n');
% starting a table environment in LaTeX.
%fprintf(f1, ['\\begin{table} \n']);
%fprintf(f1, ['\\caption{', tablename,'} \n']);
fprintf(f1, ['\\begin{longtable}', stylestr, ' \n']);
fprintf(f1, ['\\hline \n']);
fprintf(f1, ['\\multicolumn{', num2str(ncol+1), '}{|c|}{',char(tablename),'} \\\\ \n']);
fprintf(f1, ['\\hline \n']);
for jj = 1:nrow+1 % row by row
    if jj == 1; % taking care of first row(fill in column title)
        rowstring =char(corner);
        for kk = 1:ncol;
            %rowstring = [rowstring, ' & ', coltit{kk}];
            rowstring=strcat(rowstring,' & ',char(coltit{kk})); 
        end
    elseif jj > 1;
        rowstring = rowtit{jj-1};
        for kk = 1:ncol % column by column
            if isnum
                rowstring =  [rowstring, '&', num2str(datamat(jj-1, kk), '%3.2f')];
            else
                rowstring =  [rowstring, '&', datamat{jj-1, kk}];
            end
        end
    end
    fprintf(f1, [rowstring, '\\\\ \\hline \n']);
end

fprintf(f1, '\\end{longtable} \n');
%fprintf(f1, ['\\end{table} \n']);
fprintf(f1, '\\end{center} \n');
if ~tex_only
    fprintf(f1, '\\end{document} \n');
end
fclose(f1);
cd(cucd); 
if ~tex_only
    if ~isunix
        fname_system = fname(isspace(fname)==0); 
    else
        fname_system = fname; 
    end
    
    if ~isunix
        [status,result] = system(['pdflatex ',  [fname_system,'.tex'], ' -quiet']);
    else
        [status,result] = system(['pdflatex "', [fname_system,'.tex'], '" -quiet']);
    end
    if ~status
        disp('Could not create PDF') 
        disp(result); 
    end        
    delete([fname,'.aux'], [fname,'.log'])
end

if strcmp(outputpath,cucd)==0
    % Copy the Latex File
    [success_tex,message_tex]=copyfile([fname,'.tex'],outputpath);
    if success_tex==0
        warning('Could not copy TEX file');
        disp(message_tex);
    else
        delete([fname,'.aux'], [fname,'.log'],[fname,'.tex'])
    end
    
    if ~tex_only
        if status==0 
        [success_pdf,message_pdf]=copyfile([fname_system,'.pdf'],outputpath);
        if success_pdf==0
            warning('Could not copy pdf file');
            disp(message_pdf);
        else
            delete([fname_system,'.pdf'])
        end
        end 
    end
end


end